package com.cqndt.disaster.device.common.config;

import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import javax.sql.DataSource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import com.alibaba.druid.util.Utils;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import org.springframework.core.io.Resource;
import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Configuration;
import com.cqndt.disaster.device.common.enums.DataSourceType;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import com.cqndt.disaster.device.common.datasource.DynamicDataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;

@Configuration 
@MapperScan(basePackages="com.cqndt.disaster.device.dao")
public class MybatisConfig {

	@Primary
	@Bean(name="masterDataSource")
	@ConfigurationProperties(prefix="spring.datasource.master")
	public DataSource db1DataSource(DruidProperties druidProperties) {
		DruidDataSource dataSource=DruidDataSourceBuilder.create().build();
		return druidProperties.dataSource(dataSource);
	}
	@Bean
    public DynamicDataSource dataSource(
    	   @Qualifier("masterDataSource")DataSource masterDataSource) {
        Map<Object,Object> map = new HashMap<>();
        // 添加的key为String类型
        map.put(DataSourceType.db1.getDb(), masterDataSource);
        // 通过单例获取对象
        DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
        dynamicDataSource.setTargetDataSources(map);
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
        return dynamicDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dynamicDataSource);
//        factoryBean.setTypeAliasesPackage();
        // 设置mapper.xml的位置路径
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml");
        factoryBean.setMapperLocations(resources);
        return factoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager(DynamicDataSource dynamicDataSource){
        return new DataSourceTransactionManager(dynamicDataSource);
    }
    @Bean
	@ConditionalOnProperty(name="spring.datasource.druid.statViewServlet.enabled",havingValue="true")
	public FilterRegistrationBean<Filter> removeDruidFilterRegistrationBean(DruidStatProperties properties){
		// 获取web监控页面的参数
		DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
		// 提取common.js的配置路径
		String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
		String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
		final String filePath = "support/http/resources/js/common.js";
		// 创建filter进行过滤
		Filter filter = new Filter() {
			@Override
			public void init(javax.servlet.FilterConfig fc) throws ServletException{}
			@Override
			public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
					throws IOException,ServletException{
				chain.doFilter(request,response);
				// 重置缓冲区，响应头不会被重置
				response.resetBuffer();
				// 获取common.js
				String text = Utils.readFromResource(filePath);
				// 正则替换banner, 除去底部的广告信息
				text = text.replaceAll("<a.*?banner\"></a><br/>", "");
				text = text.replaceAll("powered.*?shrek.wang</a>", "");
				response.getWriter().write(text);
			}
			@Override
			public void destroy() {}
		};
		FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<Filter>();
		registrationBean.setFilter(filter);
		registrationBean.addUrlPatterns(commonJsPattern);
		return registrationBean;
	}
}